package com.cjy.dao;

import com.cjy.pojo.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface BlogRepository extends JpaRepository<Blog,Long> , JpaSpecificationExecutor<Blog> {

    @Query("select b from Blog b where b.recommend = true and b.published = true and b.status = 1")
    List<Blog> findTop(Pageable pageable);

    @Query("select b.user.id from Blog b where b.id = ?1")
    Long findUserId(Long id);

    @Query("select b from Blog b where b.published=true and b.status = 1")
    Page<Blog> findAllPublished(Pageable pageable);

    @Query("select b from Blog b where b.published=true and b.type.id=?1 and b.status = 1 and b.recommend = true ")
    Page<Blog> findAllPublishedAndType(Long id,Pageable pageable);

    @Query("select b from Blog b join b.tags t where b.published=true and t.id=?1 and b.status = 1 and b.recommend = true ")
    Page<Blog> findAllPublishedAndTags(Long id,Pageable pageable);

    @Query("select b from Blog b where b.title like ?1 or b.content like ?1 or b.description like ?1")
    Page<Blog> findAllSearch(String query, Pageable pageable);

    @Query("select function('date_format',b.createTime,'%Y') from Blog b group by function('date_format',b.createTime,'%Y') order by function('date_format',b.createTime,'%Y') desc")
    List<String> findGroupYear();

    @Query("select b from Blog b where function('date_format',b.createTime,'%Y') = ?1 and b.recommend = true and b.published = true and b.status = 1 order by b.createTime desc")
    List<Blog> findbyYear(String year);

    @Transactional
    @Modifying
    @Query("update Blog b set b.views = b.views+1 where b.id = ?1")
    int updateViews(Long id);

    @Query("select b from Blog b where b.status = 1 and b.published = true and b.recommend = true and b.type.id = ?1")
    List<Blog> findByTypeCount(Long typeId);

    @Query("select b from Blog b where b.status = 1 and b.published = true and b.recommend = true")
    List<Blog> countBlog();
}
